#ifndef __WN_PROTOCOL_H__
#define __WN_PROTOCOL_H__

#include <stdint.h>
#include <rtthread.h>

#define WN_PROTOCOL_HEADER_SIZE 8
#define WN_PROTOCOL_MAX_DATA_SIZE 256
#define MGS_LEN_MAX 256
//通信超时时间300ms
#define WN_TIMEOUT_MS   300

//设备识别码
enum device_code_t{
    device_wn   =   0x01,
    device_em   =   0x02,
    deivce_es   =   0x04,
    device_emu  =   0x05,
};

//文件类型定义
enum file_type_t{
    file_emu_update = 0x60,
    file_wn_update =0x61,
    file_wn_error_file = 0x70,
    file_wn_iv_file = 0x71,
    file_wn_power_file = 0x72,
};

#define HEAD_PLC    0x48
#define HEAD_WN     0x68
#define CODE_BROATCAST 00x00
enum func_code{
    FC_READ_REGS = 0x03,
    FC_WRITE_REG = 0x06,
    FC_WRITE_REGS = 0x10,
    FC_LOAD_STARTFRAME = 0x20,
    FC_LOAD_DATAFRAME = 0x21,
    FC_LOAD_ENDFRAME = 0x22,
    FC_READ_ERRORFILE = 0x24,
    FC_READ_OSC_FILE = 0x25,
    FC_READ_IV_FRAME = 0x26,
    FC_READ_REG1_FRAME = 0x27,
    FC_READ_REG2_FRAME = 0x28,
    FC_SET_ID_FRAME = 0x30,
};

enum plc_func_code{
    FC_READ_PLC_VERSION     = 0x0001,
    FC_READ_PLC_MACADDRESS  = 0x0002,
    FC_READ_PLC_IP = 0x0003,
    FC_SET_PLC_IP = 0x0004,
    FC_RESET_PLC = 0X0005,
    FC_READ_PLC_WHITELISTNUM = 0X0010,
    FC_READ_PLC_WHITELISTINFO = 0X0011,
    FC_ADD_PLC_WHITELIST = 0X0012,
    FC_DEL_PLC_WHITELIST = 0X0013,
    FC_READ_PLC_NETNODE = 0X0021,
    FC_PLC_TRANSFORM = 0X0120,
};

#pragma pack(1)
typedef struct wn_frame_head{
    uint8_t head;   //头
    uint8_t len;    //长度
    uint8_t addr;   //从机地址
    uint8_t code;   //功能码
}wn_frame_head_t;
typedef struct wn_plc_frame_head{
    uint8_t head;   //头
    uint8_t ctr;    //控制
    uint16_t code ;   //功能码
    uint16_t idx;   //帧序列
}wn_plc_frame_head_t;

#pragma pack()

int uart_send_data(uint8_t*data,int len);

/*
*   读取多个寄存器 0x03
*
*/
int emupacket_device_basic(uint8_t addrID,uint8_t fcode,uint8_t*outmsg);
int emupacket_read_regs(uint8_t addId,uint16_t startReg,uint16_t regNum,uint8_t*outmsg);

int emupacket_write_single_reg(uint16_t reg,uint16_t value,uint8_t*outmsg);


/*
 * 读取拓扑中的节点信息
 * */
int emupack_plc_baisc(uint16_t fcode,uint8_t*outmsg);
int empack_crc(uint8_t*outmsg,uint32_t len);
int emupack_plc_readDevice(uint8_t*outmsg);

rt_uint8_t wn_plc_readDevice();
rt_uint8_t wn_plc_readMac();
rt_uint8_t wn_plc_readVersion();
rt_uint8_t wn_plc_readWhiteListNum();
rt_uint8_t wn_plc_readWhiteListInfo();
rt_uint8_t wn_plc_addWhiteList(rt_uint8_t* deviceData,rt_uint16_t deviceNum);
rt_uint8_t wn_plc_delWhiteList(rt_uint8_t* deviceData,rt_uint16_t deviceNum);
rt_uint8_t wn_plc_readNetNodes(rt_uint16_t* startnode,rt_uint16_t nodeNum);
rt_uint8_t wn_plc_transform(rt_uint32_t* address,rt_uint8_t* wnData,rt_uint16_t wnDataLen);



#endif
